<template>
  <div class="roll-room mt-6">
    <!-- 返回按钮 -->
    <el-button
      @click="handleBack"
      class="text-white d-flex align-center back-button"
      style="z-index: 1"
      type="text"
    >
      <div class="d-flex align-center">
        <img
          src="@/static/img/icon/back.png"
          class="mr-1"
          style="width: 20px"
        />
        返回
      </div>
    </el-button>

    <div class="roll-room-container">
      <!-- 房间概况 -->
      <v-row
        class="roll-room-header d-flex"
        no-gutters
        :class="{ 'is-official': detail.room_type === 0 }"
      >
        <!-- 头像、房间名 -->
        <v-col cols="12" sm="auto" class="left d-flex flex-column align-center">
          <!-- 头像 -->
          <div class="room-avatar">
            <img v-if="detail.avatar" :src="detail.avatar" />
          </div>
          <!-- 官方标识 -->
          <div class="official-flag">官方</div>
          <!-- 房间名 -->
          <div class="room-name text-overflow text-center">
            {{ detail.nickname }}
          </div>
        </v-col>

        <v-col cols="12" sm="auto" class="middle">
          <div class="d-flex flex-column justify-center" style="height: 100%">
            <div class="d-flex justify-center d-sm-block align-center">
              <!-- 房间号 -->
              <div>房间号：{{ detail.id }}</div>
              <div class="ml-3 ml-sm-0 my-2">
                <!-- 是否需要密码 -->
                <span v-if="detail.lottery_status === 0">
                  房间{{ detail.is_password_room ? "有" : "无" }}密码
                </span>
                <!-- 活动已结束 -->
                <span v-else>活动已结束</span>
              </div>

              <!-- 审核中 -->
              <span v-if="isShowAuditTips">房间审核中</span>
            </div>

            <v-row class="my-2 justify-center" no-gutters>
              <!-- 加入房间 -->
              <v-col cols="auto" md="12" v-if="isShowJoinRoomButton">
                <v-btn
                  color="#E9B10E"
                  class="mt-1"
                  @click="handleJoinRoom"
                  size="small"
                >
                  <div class="align-center text-black">
                    <!-- 密码房加锁 -->
                    <i class="el-icon-lock" v-if="detail.is_password_room"></i>
                    加入房间
                  </div>
                </v-btn>
              </v-col>

              <!-- 编辑房间 -->
              <v-col cols="auto" md="12" v-if="isShowEditButton">
                <v-btn
                  size="small"
                  color="#E9B10E"
                  @click="handleEditRoom"
                  class="text-black"
                  >编辑房间</v-btn
                >
                <p v-if="detail.reject_reason">
                  审核失败：{{ detail.reject_reason }}
                </p>
              </v-col>

              <!-- 取消房间 -->
              <v-col
                cols="auto"
                md="12"
                v-if="isShowCancelButton"
                class="ml-2 ml-md-0 mt-md-2 text-black"
              >
                <v-btn size="small" @click="handleCancelRoom">取消房间</v-btn>
              </v-col>
            </v-row>
          </div>
        </v-col>

        <v-col cols="12" sm="auto" class="right">
          <!-- 简介 -->
          <div v-if="detail.id">
            <!-- <p class="roll-room-subtitle">房间简介</p> -->
            <div class="roll-room-desc">
              <div class="text-white">
                活动时间：{{ formatTime(detail.start_time) }} -
                {{ formatTime(detail.lottery_time) }}
                <br />
                最大中奖人数：{{ detail.skin_list.length }}人
                <br />
                最大参与人数：{{ detail.max_join_num }}人
                <br />
                限时最低充值门槛：{{ detail.recharge_amount }}
                <br />
              </div>
              <span style="white-space: pre-wrap;">{{ detail.room_desc }}</span>
            </div>
          </div>
        </v-col>
      </v-row>

      <!-- 奖池信息 -->
      <template v-if="detail.lottery_status === 0">
        <v-row class="prize-pool my-3 d-flex" no-gutters>
          <v-col cols="12" sm="6" class="d-flex align-center">
            <span class="prize-pool-title mr-3">奖池奖品</span>
            <div class="pr-2 mr-2" style="border-right: 1px solid #868492">
              共<span class="number">{{ detail.skin_list.length }}</span
              >件饰品
            </div>
            <div>
              价值<span class="number">{{ detail.prize_pool }}</span
              >硬币
            </div>
          </v-col>

          <v-col cols="12" sm="6" class="d-flex justify-end">
            <v-btn
              size="small"
              @click="handlePushSkin"
              v-if="isShowPushSkinButton"
              >存入饰品</v-btn
            >
          </v-col>
        </v-row>
     </template>

      <!-- 中奖记录 -->
      <template v-else>
        <v-row class="prize-pool my-3 d-flex" no-gutters>
          <v-col cols="12" sm="6" class="d-flex align-center">
            <span class="prize-pool-title mr-3">中奖记录</span>
            <div class="pr-2 mr-2" style="border-right: 1px solid #868492">
              已送出<span class="number">{{ detail.winning_users.length }}</span
              >件饰品
            </div>

            <div>
              价值<span class="number">{{ totalPrice }}</span
              >硬币
            </div>
          </v-col>
        </v-row>
      </template>

        <skin-list
          :is-plain="detail.lottery_status === 0"
          :skin-list="skinList"
        ></skin-list>

      <!-- 参与人员 -->
      <v-row class="prize-pool my-3 d-flex" no-gutters>
        <v-col cols="12" sm="6" class="d-flex align-center">
          <span class="prize-pool-title mr-3">参与人员</span>
          <div class="pr-2 mr-2">
            共计<span class="number">{{ detail.join_users.length }}</span
            >人
          </div>
        </v-col>
      </v-row>

      <!-- 参与人员列表 -->
      <v-row no-gutters style="background: #2b2c36; font-size: 12px">
        <v-col
          cols="4"
          sm="2"
          md="1"
          v-for="user in detail.join_users"
          :key="user.user_id"
          class="d-flex flex-column join-item text-center my-3"
        >
          <div style="width: 100%" class="text-center">
            <img :src="user.avatar" alt="" />
          </div>
          <span class="mt-1 text-overflow text-center">{{
            user.nickname
          }}</span>
        </v-col>
      </v-row>
    </div>

    <choose-skin-dialog
      ref="skinDialog"
      :room-id="roomId"
      @close="getRoomDetail"
    ></choose-skin-dialog>

    <confirm-box ref="confirmBox"></confirm-box>

    <edit-room-dialog
      v-model="isShowEditDialog"
      @close="isShowEditDialog = false"
      ref="editRoomDialog"
      :room-id="roomId"
      @refresh="getRoomDetail"
    ></edit-room-dialog>
  </div>
</template>

<script lang="ts">
import { RollService } from "@/services/RollService";
import { RoomDetail } from "@/types/roll";
import { processImageUrl, processRoomItem } from "@/utils";
import { useStore } from "@/store";

import { defineComponent, ref, computed } from "vue";
import SkinList from "./components/SkinList.vue";
import ChooseSkinDialog from "./components/ChooseSkin/Dialog.vue";
import { RouteLocationNormalized, useRoute, useRouter } from "vue-router";

// Todo: 转公共组件
import ConfirmBox from "../user/backpack/components/ConfirmBox.vue";
import EditRoomDialog from "./components/CreateRoomDialog.vue";

let routeFrom: RouteLocationNormalized;

export default defineComponent({
  setup() {
    const store = useStore();
    const route = useRoute();
    const router = useRouter();

    return {
      detail: ref<Partial<RoomDetail>>({
        skin_list: [],
        join_users: [],
        winning_users: [],
        prize_pool: 0,
      }),
      userInfo: computed(() => store.getters.userInfo),
      roomId: Number(route.params.id),
      router,
      route,
      isShowEditDialog: ref(false),
      password: ref(""),
    };
  },

  methods: {
    getRoomDetail() {
      RollService.getRoomDetail(this.roomId).then((res) => {
        this.detail = processRoomItem(res.data.data);
        this.detail.join_users = this.detail.join_users.map((item) => ({
          ...item,
          avatar: processImageUrl(item.avatar),
        }));
        this.detail.winning_users = this.detail.winning_users.map((item) => ({
          ...item,
          avatar: processImageUrl(item.avatar),
        }));
        this.autoOpenDialog();
        // for (let i = 0; i < 100; i++) {
        //   this.detail.join_users.push(this.detail.join_users[0]);
        // }
      });
    },

    handleJoinRoom() {
      if (this.detail.is_password_room) {
        this.$refs.confirmBox.showInput("请输入密码").then((password) => {
          this.password = password;
          this.joinRoom();
        });
        return;
      }

      this.joinRoom();
    },

    joinRoom() {
      RollService.joinRoom({
        free_room_id: this.detail.id as number,
        password: this.password,
      }).then(() => {
        this.$notify.success("加入房间成功");
        this.getRoomDetail();
      });
    },

    formatTime(t: number) {
      return this.$dayjs.unix(t).format("YYYY-MM-DD HH:mm:ss");
    },

    handlePushSkin() {
      if (this.detail.skin_list?.length >= this.detail.max_join_num) {
        // 饰品已达上限
        this.$notify.warning("饰品数量不可超过最大参与人数");
        return;
      }

      this.$refs.skinDialog.show();
    },

    handleCancelRoom() {
      this.$refs.confirmBox.show("确定取消房间？").then(() => {
        this.cancelRoom();
      });
    },

    cancelRoom() {
      RollService.cancelRoom(this.roomId).then(() => {
        this.$notify.success("房间取消成功");
        this.handleBack();
      });
    },

    handleEditRoom() {
      this.$refs.editRoomDialog.setEditData(this.detail);
      this.isShowEditDialog = true;
    },

    handleBack() {
      if (routeFrom?.name === "roll") {
        this.router.go(-1);
      } else {
        this.router.replace("/roll");
      }
    },

    autoOpenDialog() {
      if (!this.userInfo) return;
      // @ts-ignore
      if (window.autoOpenPushDialog) {
        this.$refs.skinDialog && this.$refs.skinDialog.show();
        // @ts-ignore
        window.autoOpenPushDialog = false;
      }
    },
  },

  created() {
    this.getRoomDetail();
  },

  beforeRouteEnter(to, from, next) {
    // 用于回退按钮
    routeFrom = from;
    next();
  },

  computed: {
    // 是否显示存入饰品按钮
    isShowPushSkinButton() {
      // <!-- 是房间创建者 、 活动进行时 、 房间未审核 -->
      const { lottery_status, audit_status } = this.detail;
      return this.isCreater && lottery_status === 0 && audit_status === 0;
    },

    isCreater() {
      return this.userInfo && this.userInfo.user_id === this.detail.user_id;
    },

    activityIsNotEnded() {
      const { lottery_status } = this.detail;
      return lottery_status === 0;
    },

    roomIsEnabled() {
      const { audit_status } = this.detail;
      return audit_status === 1;
    },

    // 是否显示加入房间按钮
    isShowJoinRoomButton() {
      // 非活动创建者、活动未结束、参加人数未达上限、已通过审核、未加入房间
      const { join_users, max_join_num } = this.detail;
      return (
        !this.isCreater &&
        this.activityIsNotEnded &&
        join_users.length < max_join_num &&
        this.roomIsEnabled &&
        this.userInfo &&
        join_users.findIndex(
          (user) => user.user_id === this.userInfo.user_id
        ) === -1
      );
    },

    // 是否显示编辑房间按钮
    isShowEditButton() {
      // 活动创建者、活动未结束、未通过审核
      const { audit_status } = this.detail;
      return (
        this.isCreater &&
        this.activityIsNotEnded &&
        (audit_status === 0 || audit_status === 2)
      );
    },

    // 是否显示取消房间按钮
    isShowCancelButton() {
      // 活动创建者、活动未结束、未存入饰品、未审核
      const { skin_list, audit_status } = this.detail;
      return (
        this.isCreater &&
        this.activityIsNotEnded &&
        !skin_list.length &&
        audit_status === 0
      );
    },

    // 是否显示“审核中”
    isShowAuditTips() {
      // 未开始审核、已存入饰品
      const { skin_list, audit_status } = this.detail;
      return skin_list.length && audit_status === 0;
    },

    // 已送出
    totalPrice() {
      const { winning_users } = this.detail;
      let total = 0;

      for (let i = 0; i < winning_users.length; i++) {
        total += winning_users[i].price;
      }

      return total.toFixed(2);
    },

    // 开奖前的饰品列表
    // 开奖后的中奖记录
    skinList() {
      const { lottery_status, skin_list, winning_users } = this.detail;
      if (!lottery_status) {
        return skin_list;
      }

      return skin_list.map(skin => {
        const result = winning_users.find(item => item.room_skin_id === skin.id);
        if (!result) return skin;

        return {
          ...skin,
          winner: result,
        }
      })
    },
  },

  components: {
    SkinList,
    ChooseSkinDialog,
    ConfirmBox,
    EditRoomDialog,
  },
});
</script>

<style scoped lang="scss">
$plainTextColor: #868692;
$backgroundColor: #2b2c37;

.roll-room {
  width: 90%;
  margin: 0 auto;
  max-width: 1500px;

  .roll-room-container {
    background: #1a1c24;
  }

  .roll-room-header {
    padding: 32px;
    background-color: $backgroundColor;
    border-radius: 5px;

    &.is-official {
      .left {
        .room-avatar {
          border: 1px solid #4f5175;
        }
        .official-flag {
          display: block;
        }
      }
    }

    .left {
      padding-right: 16px;
      border-right: 1px solid #444659;
      margin-right: 16px;
      width: 150px;

      .room-avatar {
        width: 100px;
        height: 100px;
        border-radius: 50%;
        overflow: hidden;

        img {
          width: 100%;
          height: 100%;
        }
      }

      .room-name {
        color: #c3c3e2;
        line-height: 1.5;
        font-size: 15px;
        width: 100%;
      }

      .official-flag {
        display: none;
      }
    }

    .right {
      margin-left: 16px;
      flex: 1;
    }
  }

  .middle {
    .el-icon-lock {
      font-size: 13px;
    }
  }

  .roll-room-subtitle {
    color: #c3c3e2;
    font-size: 15px;
    line-height: 1.5;
  }

  .roll-room-desc {
    color: $plainTextColor;
    font-size: 13px;
    line-height: 1.5;
    white-space: normal;
  }

  .prize-pool {
    color: $plainTextColor;
    font-size: 16px;
    text-indent: 6px;
    background-color: $backgroundColor;
    padding: 15px 10px;

    .prize-pool-title {
      color: #c3c3e2;
      font-size: 19px;
    }

    .number {
      color: #e9b10f;
      margin: 0 2px;
    }
  }
}

@media screen and (max-width: 768px) {
  .roll-room {
    .roll-room-header {
      .left {
        margin-left: 0;
        padding-right: 0;
        border: none;
      }

      .right {
        margin-left: 0;
      }
    }
  }
}

.join-item {
  img {
    width: 36px;
    height: 36px;
    border-radius: 50%;
  }
}

@media screen and(max-width: 600px) {
  .prize-pool {
    font-size: 12px !important;

    .prize-pool-title {
      font-size: 13px !important;
    }
  }
}
</style>
